<template>
  <el-dialog
    title="修改密码"
    :visible.sync="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="passwordForm"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="form.userName"
          placeholder="请输入用户名"
          :disabled="true"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="form.oldPassword"
          type="password"
          placeholder="请输入旧密码"
          show-password
        ></el-input>
      </el-form-item>
      
      <el-form-item label="新密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入新密码"
          show-password
        ></el-input>
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        ></el-input>
      </el-form-item>
      
      <el-form-item label="验证码" prop="code" v-if="showCode">
        <el-row :gutter="10">
          <el-col :span="14">
            <el-input
              v-model="form.code"
              placeholder="请输入验证码"
            ></el-input>
          </el-col>
          <el-col :span="10">
            <el-button @click="sendCode" :disabled="codeDisabled">
              {{ codeText }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { resetPassword, sendSmsCode } from '@/api/aggregation'

export default {
  name: 'PasswordReset',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userName: {
      type: String,
      default: ''
    },
    showCode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      dialogVisible: false,
      loading: false,
      codeDisabled: false,
      codeText: '获取验证码',
      countdown: 0,
      form: {
        userName: '',
        oldPassword: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.form.userName = this.userName
        this.resetForm()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    resetForm() {
      this.form = {
        userName: this.userName,
        oldPassword: '',
        password: '',
        confirmPassword: '',
        code: ''
      }
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.clearValidate()
      }
    },
    
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },
    
    async sendCode() {
      if (!this.form.userName) {
        this.$message.error('请先输入用户名')
        return
      }
      
      try {
        const response = await sendSmsCode(this.form.userName)
        if (response.data && response.data.success) {
          this.$message.success('验证码发送成功')
          this.startCountdown()
        } else {
          this.$message.error(response.data?.msg || '验证码发送失败')
        }
      } catch (error) {
        Logger.error('发送验证码失败:', error)
        this.$message.error('验证码发送失败')
      }
    },
    
    startCountdown() {
      this.codeDisabled = true
      this.countdown = 60
      this.codeText = `${this.countdown}秒后重试`
      
      const timer = setInterval(() => {
        this.countdown--
        this.codeText = `${this.countdown}秒后重试`
        
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeDisabled = false
          this.codeText = '获取验证码'
        }
      }, 1000)
    },
    
    async handleSubmit() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            const data = {
              userName: this.form.userName,
              oldPassword: this.form.oldPassword,
              password: this.form.password
            }
            
            // 如果需要验证码，添加到请求数据中
            if (this.showCode && this.form.code) {
              data.code = this.form.code
            }
            
            const response = await resetPassword(data)
            
            if (response.data && response.data.success) {
              this.$message.success('密码修改成功')
              this.handleClose()
              this.$emit('success')
            } else {
              this.$message.error(response.data?.msg || '密码修改失败')
            }
          } catch (error) {
            Logger.error('密码修改失败:', error)
            this.$message.error('密码修改失败，请检查网络连接')
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
